Given a pattern and a string s, find if s follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
給定一個模式和字串,判斷字串是否有遵循相同的模式。
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false
Input: pattern = "abba", s = "dog dog dog dog"
Output: false
每個pattern
的字元,只能對應到一個字串,屬於一對一個關係。a
跟b
不能同時對應dog
,a
也不能同時對應到dog
跟cat
。
首先要先建立模式對應字串與字串對應模式的對照表。
若對照表中沒有相對應的值就加入表中,若有對應值,則比較目前取得的值是否跟對應值相等。
var wordPattern = function (pattern, str) {
let matchPattern = {};
let matchStr = {};
let strArray = str.split(' ');
let strLen = strArray.length;
if (pattern.length !== strLen) {
return false;
}
for (let i = 0; i < strLen; i++) {
let p = pattern.charAt(i);
let s = strArray[i];
if (!matchPattern[p]) {
matchPattern[p] = s;
} else if (matchPattern[p] !== s) {
return false;
}
if (!matchStr[s]) {
matchStr[s] = p;
} else if (matchStr[s] !== p) {
return false;
}
};
return true;
}